<script setup lang="ts">
// 导入 Vue 的响应式 API，包括 ref 和 reactive
import { ref, reactive, onMounted } from 'vue'
// 导入 Vue Router 的 useRouter 和 useRoute 钩子，用于路由跳转和获取路由参数
import { useRouter, useRoute } from 'vue-router'
// 导入 Element Plus 组件和消息提示组件
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElCheckbox } from 'element-plus'
// 导入用户状态管理仓库
import { useUserStore } from '@/stores/user'
// 导入登录表单类型定义
import type { LoginForm } from '@/types/user'
// 导入密码存储工具函数
import {
  saveRememberedCredentials,
  loadRememberedCredentials,
  clearRememberedCredentials
} from '@/utils/passwordStorage'


const router = useRouter() // 获取路由实例
const route = useRoute() // 获取当前路由信息
const userStore = useUserStore() // 获取用户状态仓库实例

/**
 * 登录表单数据模型
 * 包含用户名、密码和记住登录状态的响应式数据
 */
const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  remember: false
})

const loginRef = ref<InstanceType<typeof ElForm>>() // 登录表单实例
const loading = ref(false) // 登录按钮加载状态

// 登录规则验证
const loginRules = {
  username: [
    { required: true, trigger: 'blur', message: '请输入用户名' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' }
  ]
}

// 处理登录
/**
 * 处理用户登录功能
 * 该函数用于验证用户登录表单并提交登录请求
 * @returns {Promise<void>} 无返回值
 */
const handleLogin = async () => {
  if (!loginRef.value) return // 登录表单不存在, 返回

  // 验证表单数据合法性
  await loginRef.value.validate(async (valid: boolean) => { // 验证表单, 返回验证结果
    if (!valid) return // 验证失败, 返回

    loading.value = true // 显示加载状态
    try {
      // 调用用户登录接口
      const result = await userStore.login({
        username: loginForm.username,
        password: loginForm.password
      })

      // 根据登录结果进行相应处理
      if (result.success) {
        // 登录成功后处理记住密码逻辑
        saveRememberedCredentials(
          loginForm.username,
          loginForm.password,
          !!loginForm.remember
        )

        ElMessage.success(result.message)

        // 检查是否有重定向参数
        const redirect = route.query.redirect as string
        if (redirect && redirect !== '/login' && redirect !== '/register') {
          router.push(redirect)
        } else {
          router.push('/home/dashboard')
        }
      } else {
        ElMessage.error(result.message)
      }
    } catch (error) {
      // 处理登录异常情况
      ElMessage.error('登录失败，请稍后重试')
    } finally {
      // 重置加载状态
      loading.value = false
    }
  })
}

// 处理记住密码复选框变化
const handleRememberChange = () => {
  if (!loginForm.remember) {
    // 如果取消记住密码，立即清除已保存的信息
    clearRememberedCredentials()
  }
}

// 处理注册
const handleRegister = () => {
  router.push('/register')
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessage.info('忘记密码功能暂未开放')
}

// 组件挂载时加载已保存的登录信息
onMounted(() => {
  const credentials = loadRememberedCredentials()
  if (credentials.remember) {
    loginForm.username = credentials.username
    loginForm.password = credentials.password
    loginForm.remember = credentials.remember
  }
})
</script>

<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">企业数字化平台管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="请输入用户名"
          prefix-icon="User"
          @keyup.enter="handleLogin"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
          @keyup.enter="handleLogin"
        >
        </el-input>
      </el-form-item>
      <div class="login-options">
        <el-checkbox
          v-model="loginForm.remember"
          @change="handleRememberChange"
          style="margin:0px 0px 25px 0px;"
        >
          记住密码
        </el-checkbox>
        <el-link type="primary" :underline="false" @click="handleForgotPassword">
          忘记密码？
        </el-link>
      </div>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%;"
          @click="handleLogin"
        >
          <span>{{ loading ? '登录中...' : '登 录' }}</span>
        </el-button>
      </el-form-item>
      <div class="register-link">
        <span>还没有账号？</span>
        <el-link type="primary" :underline="false" @click="handleRegister">
          立即注册
        </el-link>
      </div>
    </el-form>
    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2013-2025 <a href="#" target="_blank">企业数字化平台管理系统</a> 版权所有.</span>
    </div>
  </div>
</template>

<style scoped lang="scss">

.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/images/bg.png");
  background-size: cover;

  .login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 25px 25px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .title {
      margin: 0px auto 30px auto;
      text-align: center;
      color: #707070;
      font-size: 20px;
      font-weight: bold;
    }

    .el-input {
      height: 40px;

      :deep(.el-input__wrapper) {
        padding: 0 15px;
      }
    }

    .login-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
    }

    .register-link {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #606266;
    }
  }

  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;

    a {
      color: white;
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }
  }
}

</style>
